package de.haw.shc.Szenario;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import de.haw.shc.R;
import de.haw.shc.Action.Action_Impl;
import de.haw.shc.Interfaces.DeviceProperty.Device;
import de.haw.shc.JSONObjects.Light;
import de.haw.shc.JSONObjects.Szene;
import de.haw.shc.Szenario.WakeUpSzenario.WakeupAbotDialog;

public class SzenarioNotifyHandler extends Handler {
	private Map<String, List<Device>> roomMap;
	private String selectedRoom;
	private Szene szene;
	private WakeupAbotDialog wAbortDialog;
	MediaPlayer mPlayer;

	public static final int LIGHT_BLINK = 0;
	public static final int LIGHT_BLINK_ALL = 1;
	public static final int WAKEUP = 2;

	public SzenarioNotifyHandler(Map<String, List<Device>> roomMap,
			String selectedRoom) {
		this.roomMap = roomMap;
		this.selectedRoom = selectedRoom;
	}

	public SzenarioNotifyHandler(Szene szene, WakeupAbotDialog wAbortDialog,
			MediaPlayer mPlayer) {
		this.szene = szene;
		this.wAbortDialog = wAbortDialog;
		this.mPlayer = mPlayer;

	}

	@Override
	public void handleMessage(Message msg) {
		List<Device> list_of;
		int red, blue, green;

		switch (msg.what) {
		case LIGHT_BLINK_ALL: {
			Iterator<Map.Entry<String, List<Device>>> iter_Map = roomMap
					.entrySet().iterator();
			while (iter_Map.hasNext()) {
				list_of = iter_Map.next().getValue();

				red = random(0, 255);
				blue = random(0, 255);
				green = random(0, 255);

				actionLivingRoom(list_of, red, blue, green);
			}

		}
			break;

		case LIGHT_BLINK: {
			red = random(0, 255);
			blue = random(0, 255);
			green = random(0, 255);
			list_of = roomMap.get(selectedRoom);
			actionLivingRoom(list_of, red, blue, green);
		}
			break;

		case WAKEUP: {
			Action_Impl.getInstance().iniAction(szene.startSzene(),
					szene.getDeviceControll());
			wAbortDialog.showWakeupAbortDialog(mPlayer);
		}
			break;
		}
	}

	private void actionLivingRoom(List<Device> aList, int red, int blue,
			int green) {
		for (Device elem : aList) {
			if (elem.isLight()) {
				Light light = (Light) elem;
				Action_Impl.getInstance().iniAction(
						light.createColorLight(red, green, blue, 0),
						light.getDeviceControll());
				Log.d("Device on Color: ", light + " Red: " + red + " Blue: "
						+ blue + " Green: " + green);
			}
		}
	}

	public int random(int low, int high) {
		high++;
		return (int) (Math.random() * (high - low) + low);
	}
}
